from email.mime.text import MIMEText
import pprint
import smtplib
import socket

import nxlog

HOSTNAME = socket.gethostname()
FROM_ADDR = 'nxlog@{}'.format(HOSTNAME)
TO_ADDR = 'you@example.com'

def write_data(event):
    nxlog.log_debug('Python alerter received event')

    # Convert field list to dictionary
    all = {}
    for field in event.get_names():
        all.update({field: event.get_field(field)})

    # Create message from event
    pretty_event = pprint.pformat(all)
    msg = 'NXLog on {} received the following alert:\n\n{}'.format(HOSTNAME,
            pretty_event)
    email_msg = MIMEText(msg)
    email_msg['Subject'] = 'Alert from NXLog on {}'.format(HOSTNAME)
    email_msg['From'] = FROM_ADDR
    email_msg['To'] = TO_ADDR

    # Send email message
    nxlog.log_debug('Sending email alert for event')
    s = smtplib.SMTP('localhost')
    s.sendmail(FROM_ADDR, [TO_ADDR], email_msg.as_string())
    s.quit()

